<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="参数名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入参数名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="展示状态" prop="viewType">
        <el-select v-model="queryParams.viewType" placeholder="请选择展示状态" clearable size="small">
          <el-option
            v-for="dict in viewTypeOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="字段类型" prop="fieldType">
        <el-select v-model="queryParams.fieldType" placeholder="请选择字段类型" clearable size="small">
          <el-option
            v-for="dict in fieldTypeOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="类型" prop="type">
        <el-select v-model="queryParams.type" placeholder="请选择类型" clearable size="small">
          <el-option
            v-for="dict in typeOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['product:parameter:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['product:parameter:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['product:parameter:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-sort"
          size="mini"
          @click="handleSort"
          v-show="sortVisible"
          v-hasPermi="['product:parameter:edit']"
        >保存排序
        </el-button>
      </el-col>
      <LibrarySelect :refresh="getList"></LibrarySelect>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" ref="dataTable" row-key="parameterId" :data="parameterList"
              @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" class-name="allowDrag"/>
      <el-table-column label="参数名称" align="center" prop="name" class-name="allowDrag"/>
      <el-table-column label="展示状态" align="center" prop="viewType" class-name="allowDrag">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.viewType === '0'">{{ viewTypeFormat(scope.row) }}</el-tag>
          <el-tag type="warning" v-else-if="scope.row.viewType === '1'">{{ viewTypeFormat(scope.row) }}</el-tag>
          <el-tag type="success" v-else>{{ scope.row.membershipLevel }}及以上</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="字段类型" align="center" prop="fieldType" :formatter="fieldTypeFormat"
                       class-name="allowDrag"/>
      <el-table-column label="参数值" align="center" prop="fieldType" :formatter="fieldTypeFormat" class-name="allowDrag">
        <template slot-scope="scope">
          {{
            scope.row.values.map((item, index) => {
              return index < 3 ? item.name : (item.name + '......');
            }).join(',').split(',').toString()
          }}
        </template>
      </el-table-column>
      <el-table-column label="是否必填" align="center" class-name="allowDrag">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.inputType"
            active-value="1"
            inactive-value="0"
            @change="handleStatusChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="启用状态" align="center" class-name="allowDrag">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            active-value="0"
            inactive-value="1"
            @change="handleStatusChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="后台参数" align="center" class-name="allowDrag">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.viewStatus"
            active-value="1"
            inactive-value="0"
            @change="handleStatusChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width allowDrag">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['product:parameter:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['product:parameter:remove']"
            v-if="scope.row.type!=='1'"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改产品参数对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="参数名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入参数名称"/>
        </el-form-item>
        <el-form-item label="展示状态">
          <el-radio-group v-model="form.viewType">
            <el-radio
              v-for="dict in viewTypeOptions"
              :key="dict.dictValue"
              :label="dict.dictValue"
            >{{ dict.dictLabel }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="会员级别" prop="membershipLevel" v-if="form.viewType==='2'">
          <el-select v-model="form.membershipLevel" placeholder="请选择会员级别">
            <el-option label="请选择字典生成" value=""/>
          </el-select>
        </el-form-item>
        <el-form-item label="字段类型" v-if="form.parameterId === null">
          <el-radio-group v-model="form.fieldType">
            <el-radio
              v-for="dict in fieldTypeOptions"
              :key="dict.dictValue"
              :label="dict.dictValue"
            >{{ dict.dictLabel }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="展示状态">
          <el-radio-group v-model="form.viewStatus">
            <el-radio
              v-for="dict in viewStatusOptions"
              :key="dict.dictValue"
              :label="dict.dictValue"
            >{{ dict.dictLabel }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="填写类型">
          <el-radio-group v-model="form.inputType">
            <el-radio
              v-for="dict in inputTypeOptions"
              :key="dict.dictValue"
              :label="dict.dictValue"
            >{{ dict.dictLabel }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <div class="value-set" v-if="form.fieldType === '0'">
          <div class="value-title">参数值：</div>
          <div class="value-add">
            <el-button type="primary" plain @click="valueAdd">添加参数值</el-button>
          </div>
          <el-table ref="dragTable" :data="form.values" row-key="parameterValueId">
            <el-table-column label="参数值" min-width="70%" align="center" class-name="allowDrag">
              <template slot-scope="scope">
                <el-input
                  class="value-input"
                  v-if="scope.row.params.hasOwnProperty('visible') ? scope.row.params.visible : false"
                  v-model="scope.row.name"
                  :ref="'saveValueInput'+scope.row.sort"
                  size="small"
                  @keyup.enter.native="handleValueInputConfirm(scope.row)"
                  @blur="handleValueInputConfirm(scope.row)">
                </el-input>
                <el-button class="button-new-tag"
                           v-if="scope.row.params.hasOwnProperty('visible') ? !scope.row.params.visible : true"
                           :ref="'editValueButton'+scope.row.sort" size="small" @click="showValueInput(scope.row)">
                  {{ scope.row.name }}
                </el-button>
              </template>
            </el-table-column>
            <el-table-column label="操作" min-width="30%" align="center" class-name="allowDrag">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                  @click="valueDelete(scope.row)"
                  v-hasPermi="['product:parameter:edit']"
                >删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listParameter,
  getParameter,
  delParameter,
  addParameter,
  updateParameter,
  updateParameterSort
} from "@/api/mall/product/parameter";
import LibrarySelect from "@/components/XyComponents/LibrarySelect";
import Sortable from 'sortablejs'

export default {
  name: "Parameter",
  components: {LibrarySelect},
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      idNames: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 产品参数表格数据
      parameterList: [],
      // 产品参数表格原数据
      oldParameterList: [],
      // 排序保存按钮显示
      sortVisible: false,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 展示状态字典
      viewTypeOptions: [],
      // 展示状态字典
      viewStatusOptions: [],
      // 字段类型字典
      fieldTypeOptions: [],
      // 填写类型字典
      inputTypeOptions:[],
      // 类型字典
      typeOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        viewType: null,
        fieldType: null,
        status: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          {required: true, message: "参数名称不能为空", trigger: "blur"}
        ]
      }
    };
  },
  created() {
    this.getList();
    this.getDict();
  },
  methods: {
    /** 查询产品参数列表 */
    getList() {
      this.loading = true;
      listParameter(this.queryParams).then(response => {
        this.parameterList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询字典信息 */
    getDict() {
      this.getDicts("sys_view_type").then(response => {
        this.viewTypeOptions = response.data;
      });
      this.getDicts("sys_field_type").then(response => {
        this.fieldTypeOptions = response.data;
      });
      this.getDicts("sys_yes_no").then(response => {
        this.typeOptions = response.data;
      });
      this.getDicts("sys_mall_view_type").then(response => {
        this.viewStatusOptions = response.data;
      });
      this.getDicts("sys_mall_input_type").then(response => {
        this.inputTypeOptions = response.data;
      });
    },
    // 展示状态字典翻译
    viewTypeFormat(row) {
      return this.selectDictLabel(this.viewTypeOptions, row.viewType);
    },
    // 展示状态字典翻译
    viewStatusFormat(row, column) {
      return this.selectDictLabel(this.viewStatusOptions, row.viewStatus);
    },
    // 字段类型字典翻译
    fieldTypeFormat(row, column) {
      return this.selectDictLabel(this.fieldTypeOptions, row.fieldType);
    },
    // 类型字典翻译
    typeFormat(row, column) {
      return this.selectDictLabel(this.typeOptions, row.type);
    },
    // 填写类型字典翻译
    inputTypeFormat(row, column) {
      return this.selectDictLabel(this.inputTypeOptions, row.inputType);
    },
    // 取消按钮
    cancel() {
      this.reset();
      this.open = false;
    },
    // 表单重置
    reset() {
      this.form = {
        parameterId: null,
        name: null,
        viewType: '0',
        membershipLevel: null,
        fieldType: '0',
        inputType: '0',
        viewStatus: '0',
        values: []
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.parameterId)
      this.idNames = selection.map(item => item.name)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加产品参数";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      getParameter({parameterId: row.parameterId}).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改产品参数";
      });
      if (row.fieldType === '0') {
        setTimeout(() => {
          this.sortValue();
        }, 1000);
      }
    },
    handleStatusChange(row) {
      updateParameter(row).then(response => {
        this.msgSuccess("修改成功");
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid && this.valueCheckUnique()) {
          if (this.form.parameterId != null) {
            updateParameter(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addParameter(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const parameterIds = row.parameterId || this.ids;
      const name = row.name || this.idNames;
      let $this = this;
      this.$confirm('是否确认删除产品参数"' + name + '"?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        return delParameter($this.updateParamIds(parameterIds));
      }).then(() => {
        this.getList();
        this.msgSuccess("删除成功");
      }).catch((err) => {
      })
    },
    showValueInput(row) {
      row.params = {visible: true}
      this.$nextTick(function () {
        this.$refs['saveValueInput' + row.sort].focus();
      });
    },
    handleValueInputConfirm(row) {
      row.params = {visible: false}
    },
    valueAdd() {
      if (this.form.values.length < 200) {
        const newData = {
          parameterValueId: -this.form.values.length,
          name: "参数" + (this.form.values.length + 1),
          sort: this.form.values.length + 1000,
          params: {visible: false}
        };
        this.form.values.push(newData);
      } else {
        this.$message({
          message: '已达最大可添加参数量',
          type: 'warning'
        });
      }
    },
    valueDelete(row) {
      if (row !== undefined) {
        const index = this.form.values.indexOf(row);
        this.form.values.splice(index, 1);
      }
    },
    valueCheckUnique() {
      let check = '';
      let empty = 0;
      for (let i = 0; i < this.form.values.length; i++) {
        for (let j = 0; j < this.form.values.length; j++) {
          if (this.form.values[i].name === '') {
            this.form.values[i].params = {visible: true}
            empty = 1;
            break;
          } else if (this.form.values[j].name === this.form.values[i].name && this.form.values[j].sort !== this.form.values[i].sort) {
            this.form.values[i].params = {visible: true}
            check = check + ' ' + this.form.values[i].name
            break;
          }
        }
      }
      if (check !== '' || empty === 1) {
        this.$message({
          message: (empty === 1 ? '值不能为空；' : '') + (check !== '' ? '参数值：' + check + ' 已重复,' : '') + '请修改后再保存',
          type: 'warning'
        });
        return false;
      }
      for (let i = 0; i < this.form.values.length; i++) {
        this.form.values[i].sort = i - 100
      }
      return true;
    },
    sortValue() {
      const el = this.$refs.dragTable.$el.querySelectorAll(".el-table__body-wrapper > table > tbody")[0];
      Sortable.create(el, {
        handle: ".allowDrag",
        onEnd: evt => {
          const targetRow = this.form.values.splice(evt.oldIndex, 1)[0];
          this.form.values.splice(evt.newIndex, 0, targetRow);
        }
      });
    },
    /** 保存排序按钮操作 */
    handleSort() {
      let $this = this;
      this.$confirm('是否确认保存新排序?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        let params = $this.sortOrderListOnlyDynamic(this.parameterList, this.oldParameterList, 'parameterId');
        if (params.length > 0) {
          return updateParameterSort($this.updateParamIds(params));
        }
      }).then(() => {
        this.getList();
        this.sortVisible = false;
        this.msgSuccess("保存成功");
      }).catch((err) => {
      })
    }
  },
  mounted() {
    const el = this.$refs.dataTable.$el.querySelectorAll(".el-table__body-wrapper > table > tbody")[0];
    Sortable.create(el, {
      handle: ".allowDrag",
      onEnd: evt => {
        const targetRow = this.parameterList.splice(evt.oldIndex, 1)[0];
        this.parameterList.splice(evt.newIndex, 0, targetRow);
        this.sortVisible = true;
      }
    });
  }
};
</script>

<style lang="scss" scoped>
.value-set {
  .value-title {
    float: left;
    line-height: 40px;
  }

  .value-add {
    float: right;
    margin-bottom: 10px;
  }
}

.value-input {
  text-align: center
}
</style>
